using B.S.XZYData.Api.Read.Application.Command.Approval;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Approval
{
    /// <summary>
    /// 查询审批详情处理器
    /// </summary>
    public class QueryApprovalDetailHandler : IRequestHandler<QueryApprovalDetailCommand, ApiResult<ApprovalDetailResult>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _workflowInstanceRepo;
        private readonly IBaseRepository<AuditModel> _auditRepo;
        private readonly ILogger<QueryApprovalDetailHandler> _logger;

        public QueryApprovalDetailHandler(
            IBaseRepository<WorkflowInstanceModel> workflowInstanceRepo,
            IBaseRepository<AuditModel> auditRepo,
            ILogger<QueryApprovalDetailHandler> logger)
        {
            _workflowInstanceRepo = workflowInstanceRepo;
            _auditRepo = auditRepo;
            _logger = logger;
        }

        public async Task<ApiResult<ApprovalDetailResult>> Handle(QueryApprovalDetailCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<ApprovalDetailResult>();
            try
            {
                // 查询流程实例基本信息
                var workflowInstance = await _workflowInstanceRepo.GetAll()
                    .Where(x => x.Id == request.WorkflowInstanceId)
                    .Select(x => new ApprovalDetailDto
                    {
                        Id = x.Id,
                        WorkflowId = x.WorkflowId,
                        WorkOrderCode = x.WorkOrderCode,
                        WorkOrderNo = x.WorkOrderNo,
                        ProcessName = x.ProcessName,
                        ProcessCode = x.ProcessCode,
                        Title = x.Title,
                        ApplicantUserName = x.ApplicantUserName,
                        StepName = x.StepName,
                        AuditUserName = x.AuditUserName,
                        Status = x.Status,
                        CreateTime = x.CreateTime,
                        CompletedTime = x.CompletedTime
                    })
                    .FirstAsync();

                if (workflowInstance == null)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "流程实例不存在";
                    return res;
                }

                // 查询审批历史记录 - 由于DTO结构问题，暂时跳过审批历史
                // var auditRecords = await _auditRepo.GetAll()
                //     .Where(x => x.WorkflowId == request.WorkflowInstanceId.ToString())
                //     .OrderBy(x => x.CreateTime)
                //     .ToListAsync();

                res.Data = new ApprovalDetailResult 
                {
                    ApprovalInfo = workflowInstance,
                    FormData = null, // 暂时不加载表单数据
                    ApprovalHistory = new List<ApprovalHistoryDto>() // 暂时不加载审批历史
                };
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";

                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询审批详情失败，WorkflowInstanceId: {WorkflowInstanceId}", request.WorkflowInstanceId);
                res.Code = ApiEnum.Fail;
                res.Msg = "查询失败：" + ex.Message;
                return res;
            }
        }
    }
} 